import { useEffect, useRef } from "react";
import { v4 as uuid } from "uuid";
import { useForm } from "../../context/metadata-context";
import { getIEVersion } from "../../utils";

export default function HtmlEditor({ cell, value, onChange, onBlur, className }) {
  const uuidRef = useRef(uuid());
  const { params, urlPrefix } = useForm().root;
  useEffect(() => {
    // 初始化ueditor
    var imageUrl = "/attachment/ueditor-upload" + (getIEVersion === -1 ? "?package_id=" : "?isIE=1&package_id=") + params.package_id;
    if (urlPrefix && urlPrefix.length > 0) {
      imageUrl = urlPrefix.trimEnd("/") + imageUrl;
    }
    var editor = window.UE.getEditor(uuidRef.current, {
      toolbars: [
        [
          "fontfamily", //字体
          "fontsize", //字号
          "lineheight", //行间距
          "bold", //加粗
          "italic", //斜体
          "underline", //下划线
          "justifyleft", //居左对齐
          "justifycenter", //居中对齐
          "justifyright", //居右对齐
          "forecolor", //字体颜色
          "backcolor", //背景色
          "insertorderedlist", //有序列表
          "insertunorderedlist", //无序列表
          "simpleupload", //单图上传
          "inserttable", //插入表格
          "link", //超链接
          "unlink", //取消链接
          "undo", //撤销
          "redo", //重做
          "fullscreen", //全屏
        ],
      ],
      initialFrameWidth: "100%",
      enableAutoSave: false,
      autosave: false,
      imageUrl: imageUrl,
      readonly: false,
      wordCount: false,
      autoSyncData: false,
      zIndex: 999990,
      elementPathEnabled: false,
      tableDragable: false,
      autoHeightEnabled: false,
      initialFrameHeight: cell?.props?.height || 300,
    });
    editor.addListener("ready", function () {
      // 确保UE加载完成后，放入内容。
      editor.setContent(value || "");
    });
    editor.addListener("contentChange", function () {
      onChange(editor.getContent());
    });
    //失去焦点事件
    editor.addListener("blur", function () {
      onBlur();
    });

    return () => {
      if (editor && editor.container) {
        //销毁ueditor
        editor.destroy();
      }
    };
  }, []);

  return (
    <div className={className + "html-editor"}>
      <script id={uuidRef.current} name="content" type="text/plain"></script>
    </div>
  );
}
